/**
 * @constructor aliyun form
 */

import React from 'react';
import PropTypes from 'prop-types';
import { Field, Button, Message, Radio } from '@teamix/ui';
import exceed from 'utils/apimap';
import ImportProjectListModal from 'components/importProjectListModal';
import AccountMessage from '../accountMessage';
import LoadingAccount from '../accountMessage/loading';
import CONSTANTS from 'utils/constants.js';
import track from 'utils/track';
import { navigateOpen } from 'utils/router';
import './index.scss';
import intl from '../../../locale';

const { PLATFORM_TYPES } = CONSTANTS;

export default class ImportProjectByUrlModal extends React.Component {
  static propTypes = {
    platform_type: PropTypes.string,
  };

  static defaultProps = {
    platform_type: 'ALIYUN',
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    this.state = {
      isFullScreenModalShow: false,
      accountInfo: {},
      isGetttingAccount: false,
      isFirst: true, // 阿里云只有oAuth，一致为true
      // tb关联的第三方帐号
      tbAliens: [],
      // 默认选择
      bindType: 'aliyun',
      // 是否绑定失败
      isBindFail: false,
      // aliyunReferInfos: [
      //   {
      //     refer: 'aliyun',
      //     name: '阿里云',
      //   },
      //   {
      //     refer: 'aliyun_ram',
      //     name: '阿里云RAM帐号',
      //   },
      // ],
    };
  }

  componentDidMount() {
    // 先获取三方绑定，绑定0个，选择一个区授权；绑定1个直接显示；绑定2个，选择其一去绑定
    this.getTbAliens();
  }

  getTbAliens = () => {
    const { platform_type } = this.props;
    this.setState({
      isGetttingAccount: true,
    });

    this.props.setDisabled(true);
    exceed
      .fetch({
        api: 'user.tb.aliens',
      })
      .then((response) => {
        const result = response.slice(1);
        const aliyunArr =
          result.filter((item) => {
            return item.refer === 'aliyun';
          }) || [];
        const aliyunRamArr =
          result.filter((item) => {
            return item.refer === 'aliyun_ram';
          }) || [];

        const data = [];
        if (aliyunArr[aliyunArr.length - 1]) {
          data.push(aliyunArr[aliyunArr.length - 1]);
        }

        if (aliyunRamArr[aliyunRamArr.length - 1]) {
          data.push(aliyunRamArr[aliyunRamArr.length - 1]);
        }

        // aliens只有1个，自动绑定,获取帐号信息
        if (data.length === 1) {
          this.bindAccount(
            {
              platform_type,
              platform_host:
                (PLATFORM_TYPES[platform_type] && PLATFORM_TYPES[platform_type].host) || '',
              token: '',
              token_encrypted_type: 'text',
              override: true,
              account_type: data[0].refer,
            },
            (accountInfo) => {
              if (data && accountInfo) {
                this.setState({
                  tbAliens: data,
                  accountInfo,
                  isGetttingAccount: false,
                });

                this.props.setDisabled(false);
              } else {
                // 授权失败则重新走绑定流程
                this.setState({
                  isGetttingAccount: false,
                  tbAliens: [],
                  isBindFail: true,
                });

                this.props.setDisabled(false);
              }
            },
          );
          return;
        }
        // 0个需要授权， 1个需要选择绑定
        this.setState({
          tbAliens: data,
          isGetttingAccount: false,
        });

        this.props.setDisabled(false);
      })
      .fail((err) => {
        this.setState({
          isGetttingAccount: false,
        });

        this.props.setDisabled(false);
        console.error(err);
      });
  };

  handleOk = () => {
    const { accountInfo, tbAliens, bindType } = this.state;
    // 已绑定帐号直接打开弹窗
    if (Object.keys(accountInfo).length) {
      this.setState({
        isFullScreenModalShow: true,
      });
    }
    if (!tbAliens.length) {
      Message.error({
        title: intl.get({
          id: 'code-assets.importProjectModal.aliyun.SelectAnAuthorizationMethod',
          defaultMessage: '请选择授权方式',
        }),
      });
    }
    if (tbAliens.length === 2) {
      this.chooseAccountBind(bindType);
    }
  };

  // 选择一个进行绑定
  chooseAccountBind = (refer) => {
    const { platform_type } = this.props;
    const data = {
      platform_type,
      platform_host: (PLATFORM_TYPES[platform_type] && PLATFORM_TYPES[platform_type].host) || '',
      token: '',
      token_encrypted_type: 'text',
      override: true,
      account_type: refer,
    };

    this.bindAccount(data, (accountInfo) => {
      if (accountInfo) {
        this.setState({
          accountInfo,
          isFullScreenModalShow: true,
        });
      } else {
        this.setState({
          isBindFail: true,
        });
      }
    });
  };

  // 绑定帐号
  bindAccount = (data, cb) => {
    exceed
      .fetch({
        api: 'projects.import.account.aliyun.post',
        data,
      })
      .then((result) => {
        cb && cb(result);
      })
      .fail((err) => {
        cb && cb();
        console.error(err);
      });
  };

  unbindCallback = () => {
    this.setState({
      accountInfo: {},
    });
  };

  goBindAccount = (bindType) => {
    track({
      action: 'bind_account',
      page: 'Dialog-ImportRepo',
      type: 'import code.aliyun',
      control: bindType === 'aliyun' ? 'bind master account' : 'bind subaccount',
    });

    const targetUrl = `${window.location.origin}/?auto_bind=${bindType}`;
    window.location.href = `https://account.teambition.com/${bindType}/bind?next_url=${encodeURIComponent(
      targetUrl,
    )}`;
  };

  // 解绑后的操作
  handleUnbind = () => {
    this.resetData();
    this.getTbAliens();
  };

  resetData = () => {
    this.setState({
      isFullScreenModalShow: false,
      accountInfo: {},
      isGetttingAccount: false,
      isFirst: true,
      // tb关联的第三方帐号
      tbAliens: [],
    });
  };

  render() {
    const {
      isFullScreenModalShow,
      accountInfo,
      isGetttingAccount,
      isFirst,
      tbAliens,
      bindType,
      isBindFail,
    } = this.state;

    if (isGetttingAccount) {
      return <LoadingAccount />;
    }

    let msgTitle = '';
    let description = null;
    let msgType = !tbAliens.length && isBindFail ? 'error' : 'notice';
    if (!tbAliens.length) {
      // 云效环境
      description = (
        <div>
          <Button
            warning={isBindFail}
            type="normal"
            onClick={() => {
              navigateOpen('https://code.aliyun.com/', '_blank');
            }}
            size="small"
            style={{ marginRight: 12 }}
          >
            {intl.get({
              id: 'code-assets.importProjectModal.aliyun.Register',
              defaultMessage: '前往注册',
            })}
          </Button>
        </div>
      );

      msgTitle = intl.get({
        id: 'code-assets.importProjectModal.aliyun.InAlibabaCloudCodeDoes',
        defaultMessage: '在阿里云代码不存在对应的帐号',
      });
      msgType = 'warning';
    }

    if (tbAliens.length === 2) {
      description = (
        <div>
          <Radio.Group
            value={bindType}
            onChange={(value) => {
              this.setState({ bindType: value });
            }}
          >
            <Radio value="aliyun">
              {intl.get({
                id: 'code-assets.importProjectModal.aliyun.BindAnAlibabaCloudAccount',
                defaultMessage: '绑定主帐号',
              })}
            </Radio>
            <Radio value="aliyun_ram">
              {intl.get({
                id: 'code-assets.importProjectModal.aliyun.BindARamAccount',
                defaultMessage: '绑定 RAM 帐号',
              })}
            </Radio>
          </Radio.Group>
        </div>
      );

      msgTitle = intl.get({
        id: 'code-assets.importProjectModal.aliyun.SelectAnAccount',
        defaultMessage: '请选择帐号',
      });
    }

    const title = (
      <div className="aliyun-message-content">
        <div>{msgTitle}</div>
        {description}
      </div>
    );

    // 默认选中第一个
    return (
      <React.Fragment>
        {Object.keys(accountInfo).length ? (
          <AccountMessage accountInfo={accountInfo} unbindCallback={this.unbindCallback} />
        ) : (
          <Message
            title={title}
            type={msgType}
            className={`aliyun-message ${tbAliens.length === 2 ? 'radios' : 'btns'}`}
          />
        )}

        {isFullScreenModalShow ? (
          <ImportProjectListModal
            accountInfo={accountInfo}
            isModalOpen={isFullScreenModalShow}
            closeModal={() => {
              this.setState({
                isFullScreenModalShow: false,
              });
            }}
            isFirst={isFirst}
          />
        ) : null}
      </React.Fragment>
    );
  }
}
